<template>
  <el-dialog
    :modelValue="visible"
    @update:modelValue="$emit('update:visible', false)"
    title="管理员添加"
    width="30%"
  >
    <el-form :ref="'addAdminForm'" :model="ruleForm" :rules="rules" label-width="120px">
      <el-form-item label="用户名" prop="adminname">
        <el-input v-model="ruleForm.adminname" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="ruleForm.password" />
      </el-form-item>
      <el-form-item label="管理员等级" prop="level">
        <el-radio-group v-model="ruleForm.role">
          <el-radio :label="1">超级管理员</el-radio>
          <el-radio :label="2">普通管理员</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">取消</el-button>
        <el-button type="primary" @click="subAddAdminForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref } from "vue";
import { addAdminDataApi } from "../../api/admin";
defineProps(["visible"]);

const emit = defineEmits(["update:visible", "requestData"]);

const addAdminForm = ref(null);

// 声明
const ruleForm = ref({
  adminname: "",
  password: "",
  role: 1,
  checkedKeys: "",
});

// 表单验证的格式
const rules = ref({
  adminname: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 8, message: "用户名长度应为3-8位", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 10, message: "密码长度应为6-10位", trigger: "blur" },
  ],
  role: { required: true, message: "必须选择一个等级", trigger: "blur" },
});

// 重置表单的方法
const resetForm = () => {
  ruleForm.value = {
    adminname: "",
    password: "",
    role: 1,
  };
};

const subAddAdminForm = () => {
  addAdminForm.value.validate(async (isPass) => {
    if (isPass) {
      try {
        await addAdminDataApi(ruleForm.value);
        // console.log(ruleForm.value);
        resetForm();
        emit("requestData");
        emit("update:visible", false);
      } catch (error) {
        console.log(error);
      }
    }
  });
};
</script>
<style lang="scss">
.button-box-add-admin {
  display: flex;
  flex-direction: row-reverse;
}
</style>
